import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController, Events } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { URLSearchParams } from '@angular/http';
import { TranslateService } from '@ngx-translate/core';

import { ProductOptionModalPage } from '../product-option-modal/product-option-modal';
import { HelperService } from "../../providers/services.helper";
import { ApiService } from "../../providers/services.api";
import { GlobalData } from "../../providers/GlobalData";

/**
 * Generated class for the ProductListPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-product-list',
  templateUrl: 'product-list.html',
})
export class ProductListPage {

  productList: Array<{ id: number, name: string, photo: string }>;
  productCount: Number = 0;
  category_id: string;
  productLimit: number;
  productLimitFrom: number;
  modalShownTime: number = 0;

  constructor(public navCtrl: NavController,
    private helperService: HelperService,
    public navParams: NavParams,
    public translate: TranslateService,
    public events: Events,
    public global: GlobalData,
    public api: ApiService,
    public modalCtrl: ModalController,
    public storage: Storage) {
    this.init();
  }

  init() {
    this.category_id = this.navParams.data['id'];
    this.productLimit = 12;
    this.productLimitFrom = 0;
    this.productList = [];

  }

  // open modal for item option(s)
  openItemOption(product) {
    this.global.product = product;
    this.addToCart(product);
    console.log("set product: ", this.global.product);
  }

  newCart(table_num) {
    return new Promise((resolve, reject) => {
      this.storage.get('settings').then(setting => {
        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('locale', setting.locale);
        urlSearchParams.append('token', setting.token);
        urlSearchParams.append('check_out_warehouse_id', setting.warehouse_id);
        urlSearchParams.append('user_id', this.global.curMember.user_id == 0 ? null : this.global.curMember.user_id);
        this.api.newCart(urlSearchParams.toString()).then(data => {
          console.log('newCart success:', data);
          resolve(data['invoice_id']);
        }, error => {
          console.log('newCart error:' + error);
          this.helperService.showToast(error);
          reject(error);
        });
      });
    });
  }

  addToCart(product) {
    if (this.global.curCart.id == null) {
      console.log('invoice id is null, new cart');
      this.newCart(0).then(invoiceId => {
        this.global.curCart['id'] = invoiceId;
        this.addToCart(product);
      }, error => {

      });
      return;
    }

    if (this.global.curCart.payed_amount > 0) {
      this.helperService.showToast(this.translate.instant('THIS_CART_IS_PAYED'));
      return;
    }
    console.log(product);
    this.helperService.showLoading();

    var addOptions: Array<{ dictionary: number, option: number }> = [];
    for (let spec of product.specifications) {
      if (spec.enabled && spec.selectible && spec.options.length) {
        addOptions.push({
          dictionary: spec.dictionary,
          option: spec.options[0].id
        });
      }
    }

    var spec = [];
    for (let opt of addOptions) {
      spec.push(opt);
    }

    if (product.addons == null) {
      product.addons = [];
    }

    var originAddons = product.addons;
    for (var i = 0; i < originAddons.length; i++) {
      originAddons[i].qty = 0;
    }

    console.log('addToCart spec: ');
    console.log(spec);

    console.log('addToCart addons: ');
    console.log(originAddons);

    this.storage.get('settings').then(setting => {
      let urlSearchParams = new URLSearchParams();
      urlSearchParams.append('locale', setting.locale);
      urlSearchParams.append('token', setting.token);
      urlSearchParams.append('warehouse_id', setting.warehouse_id);
      urlSearchParams.append('action', 'add');
      urlSearchParams.append('product_id', product.id);
      urlSearchParams.append('qty', '1');
      urlSearchParams.append('user_id', this.global.curMember.user_id == 0 ? null : this.global.curMember.user_id);
      urlSearchParams.append('invoice_id', this.global.curCart.id);
      urlSearchParams.append('spec', JSON.stringify(spec));
      urlSearchParams.append('addons', JSON.stringify(originAddons));
      urlSearchParams.append('invoice_charges', JSON.stringify(this.global.curCart.invoice_charges));
      urlSearchParams.append('calling_type', 'f_b');
      this.api.setCart(urlSearchParams.toString()).then(cart => {
        this.global.curCart = cart['data'];

        for (let pd of cart['data']['products']) {
          if (pd['item_id'] == cart['item_id']) {
            this.global.product = pd;
            console.log('set global product:' + pd);
          }
        }
        this.global.curTab = 'order';

        if (spec.length || originAddons.length) {
          this.openItemModal(product);
        }
        console.log('addtoCart success:', cart);
        this.helperService.hideLoading();
      }, (error) => {
        console.log('addtoCart error:' + error);
        this.helperService.hideLoading();
        this.helperService.showToast(error);
      });
    });
  }

  openItemModal(product) {
    let productOptionModal = this.modalCtrl.create(ProductOptionModalPage, product);
    productOptionModal.onDidDismiss(data => {
      console.log(data);
    });
    productOptionModal.present();
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ProductListPage');
    console.log(this.navParams);
    this.loadProductList('init', null);
  }

  loadProductList(mode, doer) {
    console.log("begin load product: " + mode + ", in loadProductList count: " + this.productCount);

    if (mode != 'more' || this.productList.length == 0) {
      this.productLimitFrom = 0;
      this.productLimit = 12;
      this.productCount = 0;
      this.productList = [];
    } else {
      this.productLimitFrom += this.productLimit;
    }

    this.storage.get('settings').then((setting) => {
      let urlSearchParams = new URLSearchParams();
      urlSearchParams.append('locale', setting.locale);
      urlSearchParams.append('token', setting.token);
      urlSearchParams.append('calling_from', 'pos');
      urlSearchParams.append('limit_from', this.productLimitFrom.toString());
      urlSearchParams.append('limit', this.productLimit.toString());
      urlSearchParams.append('warehouse_id', setting.warehouse_id);
      urlSearchParams.append('category_ids[0]', this.category_id);
      this.api.getProductList(urlSearchParams.toString()).then(data => {
        for (let product of data['data']['products']['list']) {
          product.haveSpec = false;
          for (let spec of product.specifications) {
            if (spec.enabled && spec.selectible && spec.options.length) {
              product.haveSpec = true;
            }
          }
          this.productList.push(product);
        }
        this.productCount = data['data']['products']['count'];
        if (doer != null) {
          doer.complete();
        }
        console.log('getProductList success: ', data['data']['products']['list'][0]['categories'][0], 'count: ', this.productCount);
      }, (error) => {
        console.log('getProductList error: ' + error);
        this.helperService.showToast(error);
        if (doer != null) {
          doer.complete();
        }
      });
    });
  }
}
